import { useEffect, useRef, useState } from 'react';
import './Shuju.less';
import ReactEcharts from 'echarts-for-react';
import * as echarts from "echarts";
import axios from 'axios';
import styled from'styled-components';

// 定义一个函数用于生成不同的颜色
const getRandomColor = () => {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
};

// 定义样式化的组件，用于设置mount盒子的样式，使其不出现滚动条
const MountBox = styled.div`
    width: 100%;
    height: 400px; /* 你可以根据需要调整高度 */
    overflow: hidden; /* 隐藏超出盒子的内容，避免出现滚动条 */
`;

// 定义样式化的组件，用于设置mount2盒子的样式，使其不出现滚动条
const Mount2Box = styled.div`
    width: 100%;
    height: 400px; /* 你可以根据需要调整高度 */
    overflow: hidden; /* 隐藏超出盒子的内容，避免出现滚动条 */
`;

export default function Shuju() {
    let [list, setList] = useState([]);
    let [list2, setList2] = useState([]);
    // 使用useRef保存echarts实例和DOM元素是否准备好的状态
    const chartRef = useRef({
        myChart: null,
        isMounted: false
    });

    // 新增ref用于保存mount2对应的echarts实例
    const chartRef2 = useRef({
        myChart: null,
        isMounted: false
    });

    let getAdmissions = async () => {
        let { data } = await axios.get('http://localhost:3000/patientinfo');
        console.log(data);
        if (data.code === 200) {
            setList2(data.data);
        }
    };

    useEffect(() => {
        getorder();
        getAdmissions();

        // 监听DOM元素是否挂载完成
        const mountDiv = document.getElementById('mount');
        if (mountDiv) {
            chartRef.current.myChart = echarts.init(mountDiv);
            chartRef.current.isMounted = true;
        }

        const mountDiv2 = document.getElementById('mount2');
        if (mountDiv2) {
            chartRef2.current.myChart = echarts.init(mountDiv2);
            chartRef2.current.isMounted = true;
        }
    }, []);

    let getorder = async () => {
        let { data } = await axios.get('http://localhost:3000/order');
        console.log(data);
        if (data.code === 200) {
            setList(data.data);

            // 处理数据，按支付类型统计订单金额并添加颜色信息
            const processedData = processDataByPayType(data.data);

            // 数据获取成功且DOM元素和echarts实例都准备好后，更新图表
            if (chartRef.current.isMounted && chartRef.current.myChart) {
                const myChart = chartRef.current.myChart;

                const options = {
                    title: {
                        text: '不同支付类型的订单金额统计'
                    },
                    xAxis: {
                        type: 'category',
                    data: processedData.map(item => item.paytype)
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '订单金额',
                            type: 'bar',
                        data: processedData.map(item => item.orderamount),
                            itemStyle: {
                                normal: {
                                    color: function (params) {
                                        return processedData[params.dataIndex].color;
                                    }
                                }
                            }
                        }
                    ]
                };

                myChart.setOption(options);
            }
        }
    };

    // 按支付类型处理数据，统计订单金额并生成随机颜色
    const processDataByPayType = (data) => {
        const payTypeMap = new Map();
        data.forEach((item) => {
            const paytype = item.paytype;
            if (payTypeMap.has(paytype)) {
                payTypeMap.get(paytype).orderamount += item.orderamount;
            } else {
            payTypeMap.set(paytype, {
                orderamount: item.orderamount,
                paytype: paytype,
                color: getRandomColor()
            });
            }
        });
        return Array.from(payTypeMap.values());
    };

    // 处理list2数据以用于在mount2中展示柱状图的函数，根据描述状态统计人数并合并相同类型
    const processList2Data = (data) => {
        const descriptionMap = new Map();
        data.forEach((item) => {
            const description = item.description;
            if (descriptionMap.has(description)) {
                descriptionMap.get(description).count++;
            } else {
                descriptionMap.set(description, {
                    count: 1,
                    description: description,
                    color: getRandomColor()
                });
            }
        });

        // 将相同描述状态的患者数据合并为一个对象，包含总人数、描述、颜色
        const mergedData = [];
        descriptionMap.forEach((value, key) => {
            mergedData.push({
                count: value.count,
                description: key,
                color: value.color
            });
        });

        return mergedData;
    };

    useEffect(() => {
        // 当list2数据更新且mount2对应的echarts实例准备好时，更新图表
        if (chartRef2.current.isMounted && list2.length > 0) {
            const myChart2 = chartRef2.current.myChart;
            const processedData2 = processList2Data(list2);

            const options2 = {
                title: {
                    text: '不同描述状态患者人数统计'
                },
                xAxis: {
                    type: 'category',
                    data: processedData2.map(item => item.description)
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '患者人数',
                        type: 'bar',
                        data: processedData2.map(item => item.count),
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return processedData2[params.dataIndex].color;
                                }
                            }
                        }
                    }
                ]
                };

                myChart2.setOption(options2);
        }
    }, [list2]);

    return (
        <div>
            <MountBox id="mount"></MountBox>
            <Mount2Box id="mount2"></Mount2Box>
        </div>
    );
}